#文件名: fileupload.py
import sys,os,time,datetime,random
from flask import request,Flask
sys.path.append('../')
from config import base
app = Flask(__name__)

class fileupload(object):
    __prefix = ['jpg','jpeg','png','gif','mp3','mp4']
    __path = base.const.url + '/static/'
    __filesizemax = 10 * 1024 * 1024   #限制上传文件大小
    #初始化文件路径
    def upload(self,path:str,save = True,filename = 'file'):
        try:
            msg = ''
            file = request.files[filename]
            fileurl = self.__path + path
            #如果目录不存在，则先创建目录
            if not os.path.exists(fileurl):
                os.makedirs(fileurl, mode=0o777)
            filename = file.filename
            prefix = filename[filename.find('.')+1:]
            if prefix not in self.__prefix:
                msg = 'upload failed,the file type is error'
                raise ValueError
            savename = ''
            if save:
                savename = file.filename
            else:
                savename = self.makesavename() + '.' + prefix
            file.save(fileurl + savename)
            return 'success'
        except ValueError:
            return msg
        else:
            return 'error'

    def makesavename(self):
        dt_ms = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
        randstr = random.randint(10000,99999)
        return dt_ms + str(randstr)